package commons.base.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 读写空闲超时则进行一些处理
 * @author yuan<cihang.yuan@happyelements.com>
 *
 */
public class IdleTimeoutHandler extends ChannelInboundHandlerAdapter {

	/**
	 * 空闲超时配置
	 */
	private IdleTimeoutConfig idleTimeoutConfig;
	
	public IdleTimeoutHandler(IdleTimeoutConfig idleTimeoutConfig) {
		super();
		this.idleTimeoutConfig = idleTimeoutConfig;
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE && idleTimeoutConfig.getReaderIdleTimeSeconds() > 0) {
            	idleTimeoutConfig.getChannelIdleTimeoutListener().readIdleTimeout(ctx);
            } else if (event.state() == IdleState.WRITER_IDLE && idleTimeoutConfig.getWriterIdleTimeSeconds() > 0) {
            	idleTimeoutConfig.getChannelIdleTimeoutListener().writeIdleTimeout(ctx);
            } else if (event.state() == IdleState.ALL_IDLE && idleTimeoutConfig.getAllIdleTimeSeconds() > 0) {
            	idleTimeoutConfig.getChannelIdleTimeoutListener().allIdleTimeout(ctx);
            }
		}
		super.userEventTriggered(ctx, evt);
	}
	
}
